/****************************************************************************
 * 2025.3 LAPTOP-OMJU83NA
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using TMPro;
using UnityEngine.U2D;

namespace Survivor
{
	public partial class ExpUpgradePanel : UIElement,IController
	{
		private List<Button> _upgradeButtons;

		private ResLoader _resLoader;
		private SpriteAtlas _iconAtlas;
		private void Awake()
		{
			_resLoader = ResLoader.Allocate();
			_iconAtlas = _resLoader.LoadSync<SpriteAtlas>("Icon");
			
			_upgradeButtons = new();
			var expUpgradeSystem = this.GetSystem<ExpUpgradeSystem>();
			// var (items,size) = expUpgradeSystem.GetRandomExpUpgradeItem();
			for (int i = 0; i < expUpgradeSystem.ExpUpgradeItemNum; i++)
			{
				var btn = ButtonExpUpgradeTemplate.InstantiateWithParent(ExpUpgradeRoot).Show();
				_upgradeButtons.Add(btn);
			}
			ButtonSkip.onClick.AddListener(Hide);
		}

		protected override void OnShow()
		{
			base.OnShow();
			Time.timeScale = 0;  // 暂停游戏
			FlushUI();
		}

		protected override void OnHide()
		{
			base.OnHide();
			Time.timeScale = 1;
		}
		
		public void FlushUI()
		{
			var items= this.GetSystem<ExpUpgradeSystem>().GetRandomItems();

			for (int i = 0; i < items.Count; i++)
			{
				_upgradeButtons[i].GetComponentInChildren<TextMeshProUGUI>().text = items[i].Description;
				_upgradeButtons[i].onClick.RemoveAllListeners();
				_upgradeButtons[i].transform.Find("Icon").GetComponent<Image>().sprite =
					_iconAtlas.GetSprite(items[i].IconName);
				int indexCache = i;
				_upgradeButtons[i].onClick.AddListener(() =>
				{
					items[indexCache].Upgrade();
					AudioKit.PlaySound("AbilityLevelUp");
					Hide();
				});
			}
		}

		protected override void OnBeforeDestroy()
		{
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}